package com.hbsoft.util;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

@Service
public class ImageUtil {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 签名合成，图片坐标系左上角为（0，0）
     *
     * @param imgPath       图片路径
     * @param signaturePath 签名图片路径
     * @param outFilePath   合成后图片路径
     * @param xPlace        签名图片放置的x坐标
     * @param yPlace        签名图片放置的y坐标
     * @param signatureWidth        签名图片的宽
     * @param signatureHeight        签名图片的高
     * @return 是否合成成功
     * @throws
     */
    public  Boolean signatureSynthesis(String imgPath, String signaturePath, String outFilePath, int xPlace,
                                             int yPlace,int signatureWidth,int signatureHeight,String title ) throws Exception {
        logger.info("进入签名合成方法");
       /*Image srcImage = ImageIO.read(new File(imgPath));
        BufferedImage backImg = new BufferedImage(((BufferedImage) srcImage).getWidth(),((BufferedImage) srcImage).getHeight(),BufferedImage.TYPE_3BYTE_BGR);*/
       BufferedImage backImg = ImageIO.read(new File(imgPath));
        backImg.getWidth();
        backImg.getHeight();
        logger.info(" backImg.getWidth:{}, backImg.getHeight:{}", backImg.getWidth(), backImg.getHeight());

        BufferedImage signatureImg = ImageIO.read(new File(signaturePath));

        File outFile = new File(outFilePath);
        // 假如目标路径不存在,则新建该路径
        if (!outFile.getParentFile().exists()) {
            logger.info("合成后图片目标路径不存在,新建该路径");
            outFile.getParentFile().mkdirs();
        }
        // 假如目标文件不存在,则新建该文件
        if (!outFile.exists()) {
            logger.info("合成后图片目标文件不存在,新建该文件");
            outFile.createNewFile();
        }

        Graphics2D backG = backImg.createGraphics();
       // backG.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        //消除画图锯齿
      //  backG.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        logger.info("开始合成签名");
        backG.drawImage(signatureImg, xPlace, yPlace, signatureWidth, signatureHeight, null);
        backG.setColor(Color.black);
        Font font = new Font("微软雅黑", Font.BOLD, 70);
        backG.setFont(font);
        backG.drawString(title,xPlace+300, yPlace + 1040);
        backG.dispose();
        ImageIO.write(backImg, "jpg", new File(outFilePath));
        logger.info("合成签名完成");
        return true;
    }

    public static void main(String[] args) {
        ImageUtil util = new ImageUtil();
        try {
/*
            String path1 = "d:\\img\\2.png";//源文件
            String dir = "d:\\img\\";//指定的文件夹
            String fileName = "23.png";//指定的重命名
            copy2(path1, dir+fileName);*/
           util.signatureSynthesis("D:\\qrcode\\model.jpg","D:\\qrcode\\gg_877272.png","D:\\qrcode\\晋D.0253X.jpg",2340,520,950,1020,"晋D.0253X");

            File file = new File("D:\\qrcode\\晋D.0253X.jpg");
            util.handleDpi(file, 300, 300);
            //Image srcImage = ImageIO.read(new File("D:\\qrcode\\2.jpg"));
           // util.markByIcon(srcImage,"D:\\qrcode\\1.jpg","D:\\qrcode\\5.jpg",0,0,200,200);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public  void markByIcon(Image img, String srcImagePath, String targetPath, int x, int y,
                                  int w, int h) throws IOException {
        OutputStream os = null;
        try {
            logger.info("图片水印开始添加。。。");
            logger.info("图片水印输入路径" + srcImagePath);
            logger.info("图片水印输出路径" + targetPath);
            Image srcImage = ImageIO.read(new File(srcImagePath));
            BufferedImage buffImg = new BufferedImage(srcImage.getWidth(null), srcImage.getHeight(null),
                    BufferedImage.TYPE_INT_BGR);
            Graphics2D g = buffImg.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(srcImage
                            .getScaledInstance(srcImage.getWidth(null), srcImage.getHeight(null), Image.SCALE_SMOOTH),
                    0, 0, null);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1));
            g.drawImage(img, x, y, w, h, null);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
            g.dispose();
            os = new FileOutputStream(targetPath);
            //生成图片
            ImageIO.write(buffImg, "JPG", os);
            logger.info("图片水印添加成功。。。");
        } catch (Exception e) {
            logger.error("图片水印添加失败。。。", e);
            throw e;
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public  void handleDpi(File file, int xDensity, int yDensity) {
        try {
            BufferedImage image = ImageIO.read(file);
            JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(new FileOutputStream(file));
            JPEGEncodeParam jpegEncodeParam = jpegEncoder.getDefaultJPEGEncodeParam(image);
            jpegEncodeParam.setDensityUnit(JPEGEncodeParam.DENSITY_UNIT_DOTS_INCH);
            jpegEncoder.setJPEGEncodeParam(jpegEncodeParam);
            jpegEncodeParam.setQuality(0.75f, false);
            jpegEncodeParam.setXDensity(xDensity);
            jpegEncodeParam.setYDensity(yDensity);
            jpegEncoder.encode(image, jpegEncodeParam);
            image.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void copy2(String readfile,String writeFile) {
        try {
            FileInputStream input = new FileInputStream(readfile);
            File outFile = new File(writeFile);
            // 假如目标路径不存在,则新建该路径
            if (!outFile.getParentFile().exists()) {
                outFile.getParentFile().mkdirs();
            }

            FileOutputStream output = new FileOutputStream(writeFile);



            int read = input.read();
            while ( read != -1 ) {
                output.write(read);
                read = input.read();
            }
            input.close();
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
